﻿using LDC_Shop_A.Models;
using LDC_Shop_A.Models.Database;
using System;
using System.Collections.Generic;
using System.Linq;

namespace LDC_Shop_A.Service
{
    public class OrderService : IOrderService
    {
        private readonly LDC_ShopAContext _db;

        public OrderService(LDC_ShopAContext db)
        {
            _db = db;
        }

        /// <summary>
        /// 校验商品的库存
        /// </summary>
        /// <returns>够库存返回ture 不够 返回false</returns>
        public bool CheckGoodStock(List<CarGoodModel> list, out string err)
        {
            err = "";
            //什么商品？？ 将要下单的商品（购物车的商品）
            //列表 多个商品
            foreach (var carGood in list)
            {
                //商品ID 将要买的商品数量

                //去商品表查询 这个商品Id 的库存是多少 跟我将要购买商品数量作对比
                var good = _db.Goods.FirstOrDefault(x => x.GoodId == carGood.GoodId);
                if (good != null)
                {
                    //库存不足
                    if (good.Stock < carGood.Count)
                    {
                        //哪个商品不足
                        err = good.Title;
                        return false;
                    }
                }
            }
            //库存足够
            return true;
        }


        /// <summary>
        /// 扣除商品的库存
        /// </summary>
        /// <returns>够库存返回ture 不够 返回false</returns>
        public void DiffGoodStock(List<CarGoodModel> list)
        {
            //什么商品？？ 将要下单的商品（购物车的商品）
            //列表 多个商品
            foreach (var carGood in list)
            {
                //商品ID 将要买的商品数量

                //去商品表查询 这个商品Id 的库存是多少 跟我将要购买商品数量作对比
                var good = _db.Goods.FirstOrDefault(x => x.GoodId == carGood.GoodId);
                if (good != null)
                {
                    //扣除商品的库存
                    good.Stock = good.Stock - carGood.Count;
                    _db.Goods.Update(good);
                }
            }
            _db.SaveChanges();
        }
        /// <summary>
        /// 订单编号
        /// </summary>
        /// <returns></returns>
        public string GetOrderNum()
        {
            //20230617185529 + 4位随机数                                      0001,0011,9999
            return System.DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1, 10000).ToString().PadLeft(4, '0');
        }

        /// <summary>
        /// 创建订单 
        /// </summary>
        public void CreateOrder(List<CarGoodModel> list, int userId)
        {
            //创建订单和订单明细
            var order = new Order
            {
                CreateTime = System.DateTime.Now,
                //订单编号 （自己定义的订单编号规则 唯一性） 时间20230617185529+4位随机数
                OrderNum = GetOrderNum(),
                //订单总额
                OrderPrice = list.Sum(x => x.Price * x.Count),
                //订单状态（0-待付款、1-待发货（已付款）、2-待收货）
                OrderState = (int)OrderStateEnum.待发货, //1
                OrderTotal = list.Sum(x => x.Count),
                UserId = userId,
                PayTime = System.DateTime.Now,
            };
            _db.Orders.Add(order);
            //获取订单ID的前提 提交到数据库！！！
            _db.SaveChanges(); //提交 必须

            //11 服务器 挂了
            //--------------------------
            //订单创建了 商品不见了 发货的时候

            //订单明细表 将 购物车表 复制一份 存在订单明细里
            //商品 数量
            foreach (var item in list)
            {
                //循环添加明细
                var orderItem = new OrderItem
                {
                    GoodId = item.GoodId,
                    GoodCount = item.Count,
                    GoodName = item.Title,
                    GoodPrice = item.Price,
                    GoodCover = item.Photo,
                    OrderId = order.OrderId
                };
                _db.OrderItems.Add(orderItem);
            }
            _db.SaveChanges();//提交
        }
        /// <summary>
        /// 返回用户的订单模型
        /// </summary>
        public List<UserOrder> GetUserOrderList(int userId, int orderState, int pageIndex, int pageSize, out int total)
        {
            //登录用户的所有订单
            var orders = _db.Orders.Where(x => x.UserId == userId);
            //判断是否要筛选订单状态
            if (orderState > -1)
            {
                orders = orders.Where(x => x.OrderState == orderState);
            }
            total = orders.Count();
            var list = orders
                .OrderByDescending(x => x.CreateTime)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .Select(x => new UserOrder
                {
                    OrderId = x.OrderId,
                    OrderState = x.OrderState,
                    OrderNum = x.OrderNum,
                    CreateTime = x.CreateTime,
                    OrderPrice = x.OrderPrice,
                    OrderTotal = x.OrderTotal,
                })
                .ToList();

            foreach(var item in list)
            {
                item.OrderItems = _db.OrderItems.Where(x => x.OrderId == item.OrderId).ToList();
            }
            return list;
        }
        /// <summary>
        /// 返回后台订单列表
        /// </summary>
        public List<AdminOrder> GetAdminOrderList(int orderState, int pageIndex, int pageSize, out int total)
        {
            // 登录用户的所有订单
            var orders = _db.Orders.AsQueryable();
            //判断是否要筛选订单状态
            if (orderState > -1)
            {
                orders = orders.Where(x => x.OrderState == orderState);
            }
            total = orders.Count();
            var list = orders
                .Join(_db.Users, x => x.UserId, y => y.UserId, (x, y) => new AdminOrder
                {
                    OrderId = x.OrderId,
                    OrderNum = x.OrderNum,
                    OrderState=x.OrderState,
                    CreateTime = x.CreateTime,
                    OrderPrice = x.OrderPrice,
                    OrderTotal = x.OrderTotal,
                    Mobile =y.Mobile,
                    NickName=y.Nickname,
                    UserId=y.UserId,
                })
                .OrderByDescending(x => x.CreateTime)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToList();

            foreach (var item in list)
            {
                item.OrderItems = _db.OrderItems.Where(x => x.OrderId == item.OrderId).ToList();
            }
            return list;
        }
        /// <summary>
        /// 发货
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="shipCom"></param>
        /// <param name="shipNum"></param>
        public void SendOrder(int orderId,string shipCom,string shipNum)
        {
            //1、查询订单模型出来
            var order = _db.Orders.FirstOrDefault(x => x.OrderId == orderId);
            if(order != null)
            {
                //2、更新数据
                order.OrderState = (int)OrderStateEnum.待收货;
                order.ShipCom = shipCom;
                order.ShipNum = shipNum;
                order.SendTime = DateTime.Now;
                //3、提交
                _db.Orders.Update(order);
                _db.SaveChanges();
            }
        }
    }
}
